package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.CustomerFollowRecord;
import com.wing.sell.model.entity.CustomersInfo;
import com.wing.sell.model.request.CustomerFollowRecordForm;
import com.wing.sell.model.response.CustomerFollowRecordVO;
import com.wing.sell.service.CustomerFollowRecordService;
import com.wing.sell.service.CustomersInfoService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-跟进记录管理管理", tags = "#/sell/customerFollowRecord")
@RestController("customerFollowRecordController")
@RequestMapping("sell/admin/customerFollowRecord")
@RequiredArgsConstructor
@Slf4j
public class CustomerFollowRecordController {

    private final CustomerFollowRecordService customerFollowRecordService;

    private final CustomersInfoService customersInfoService;


    @ApiOperation(value = "查询所有跟进记录管理", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CustomerFollowRecordVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String followCustomer
            ,Integer customerType
    ){

        Page<CustomerFollowRecordVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }
        params.put("followCustomer", followCustomer);
        params.put("customerType", customerType);

        IPage<CustomerFollowRecordVO> list = customerFollowRecordService.pageList4app(pg,params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加跟进记录管理", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CustomerFollowRecordForm.Add.class) CustomerFollowRecordForm customerFollowRecordForm) {
        int result = customerFollowRecordService.add(customerFollowRecordForm);
        if (result == 0002) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "修改跟进记录管理", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CustomerFollowRecordForm.Update.class) CustomerFollowRecordForm customerFollowRecordForm) {
        CustomerFollowRecord customerFollowRecord = customerFollowRecordService.getById(customerFollowRecordForm.getId());
        if(customerFollowRecord == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CustomerFollowRecord.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customerFollowRecordForm, customerFollowRecord, copyOptions);
        if (customerFollowRecordService.updateById(customerFollowRecord)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除跟进记录管理", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerFollowRecordId", value = "跟进记录管理id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long customerFollowRecordId) {
        if (customerFollowRecordService.removeById(customerFollowRecordId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "审核跟进记录管理", notes = "修改状态")
    @PutMapping("/audit")
    public JsonResult audit(@Validated(CustomerFollowRecordForm.Update.class) CustomerFollowRecordForm customerFollowRecordForm) {
        CustomerFollowRecord customerFollowRecord = customerFollowRecordService.getById(customerFollowRecordForm.getId());
        if(customerFollowRecord == null){
            return JsonResult.fail("修改失败！");
        }
        customerFollowRecord.setId(customerFollowRecordForm.getId());
        customerFollowRecord.setRemark(customerFollowRecordForm.getRemark());
        customerFollowRecord.setStatus(CustomerFollowRecord.Status.audited);

        try {
            LocalDateTime checkTime = dateToLocalDate(new Date());
            customerFollowRecord.setCheckTime(checkTime);
        } catch (Exception e) {
            log.error("日期转换失败"+e.getMessage());
            return JsonResult.fail("审核失败！");
        }

        if (customerFollowRecordService.updateById(customerFollowRecord)) {

            /*String customerType = customerFollowRecordForm.getCustomerType().getDesc();
            String followResult = customerFollowRecordForm.getFollowResult();
            Long customerId = customerFollowRecordForm.getFollowCustomer();
            log.info("客户类型：{}；跟进结果类型：{}；客户ID：{}",customerType,followResult,customerId);

            CustomersInfo customersInfo = new CustomersInfo();
            customersInfo.setId(customerId);
            if ("potential".equals(customerType) && "A0001".equals(followResult)){//客户类型为潜在客户且跟进结果类型为目标达成，修改客户类型为意向客户
                log.info("-------进入潜在客户修改客户类型判断-------");
                customersInfo.setCustomerType(CustomersInfo.CustomerType.Intended);
                customersInfoService.updateById(customersInfo);
            } else if ("Intended".equals(customerType) && "A0001".equals(followResult)) {//客户类型为意向客户且跟进结果类型为目标达成，修改客户类型为正式客户
                log.info("-------进入意向客户修改客户类型判断-------");
                customersInfo.setCustomerType(CustomersInfo.CustomerType.formal);
                customersInfoService.updateById(customersInfo);
            }*/

            return JsonResult.success("审核成功！");
        }
        return JsonResult.fail("审核失败！");
    }

    // Date 转化成 LocalDateTime
    public static LocalDateTime dateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }
}
